package com.bjpowernode.crm.settings.web.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bjpowernode.crm.commons.constant.AppConstant;
import com.bjpowernode.crm.commons.utils.MD5Util;
import com.bjpowernode.crm.commons.enums.RespCode;
import com.bjpowernode.crm.commons.resp.Result;
import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:
 * Package:com.bjpowernode.crm.settings.web.controller
 * author:郭鑫
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    // redis对象
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/settings/qx/user/toLogin.do")
    public String toLogin() {
        return "settings/qx/user/login";
    }

    @RequestMapping("/settings/qx/user/login.do")
    @ResponseBody
    public Object login(String loginAct, String loginPwd, HttpServletRequest request, boolean isRemPwd, HttpServletResponse response) {
        // 结果对象
        Result result = Result.FRR();
        // 设置redis反序列化格式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        try {
            int account = userService.queryAccountByLoginAct(loginAct);
            if (account == 0) {
                result.setRespCode(RespCode.ACT_PWD_MATCH_ERR);
                return result;
            }
            // 设置储存key名称
            BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(AppConstant.CRM_LOGIN_CODE + loginAct);
            // 获得出错的次数
            Integer redValue = (Integer) boundValueOperations.get();
            // 判断出错的次数是否等于3
            if (ObjectUtil.isNotNull(redValue) && redValue == 3) {
                result.setRespCode(RespCode.ACT_LOCKED);
                return result;
            }

            // 密码加盐，MD5 + MIN_PASSWORD + MD5
            String md5 = MD5Util.getMD5(MD5Util.getMD5(loginPwd) + AppConstant.MIN_PASSWORD);
            User user = userService.queryUserByLoginActAndPd(loginAct, md5);
            // 判断用户是否存在
            if (ObjectUtil.isNull(user)) {
                // 增加redis中key的值自增1
                redisTemplate.boundValueOps(boundValueOperations.increment(1));

                // 当前时间加一天的开始时间：00点00分00秒  （// 当前时间加一天）
                Date beginOfDay = DateUtil.beginOfDay(DateUtil.tomorrow());
                long betweenDay = DateUtil.between(DateUtil.date(), beginOfDay, DateUnit.SECOND);
                System.out.println(betweenDay);
                // 设置失效时间
                boundValueOperations.expire(120, TimeUnit.SECONDS);

                // 账号密码不匹配
                result.setRespCode(RespCode.ACT_PWD_MATCH_ERR);
                return result;
            }
            // 判断账号是否失效
            // 业务规则：失效：不为空 && 登陆时间超过失效时间
            if (StrUtil.isNotEmpty(user.getExpireTime()) && DateUtil.compare(new Date(), DateUtil.parseDate(user.getExpireTime())) > 0) {
                result.setRespCode(RespCode.ACT_EXPIRE);
                return result;
            }


            // 判断账号锁定状态
            // 业务规则：锁定：不为空：状态值为0
            if (StrUtil.isNotEmpty(user.getLockState()) && StrUtil.equals("0", user.getLockState())) {
                result.setRespCode(RespCode.ACT_LOCKED);
                return result;
            }

            // 判断ip地址是否受限
            // 获取当前访问ip地址
            String remoteHost = request.getRemoteHost();
            // 业务规则：受限：不为空 && 访问的ip不包含在指定IP内//192.168.1.1,127.0.0.1
            if (StrUtil.isNotEmpty(user.getAllowIps()) && !StrUtil.contains(user.getAllowIps(), remoteHost)) {
                result.setRespCode(RespCode.IP_NOT_ALLOW);
                return result;
            }

            // 判断是否勾选记住我如果勾选存放在cookie
            if (isRemPwd) {
                Cookie c1 = new Cookie("loginAct", loginAct);
                c1.setMaxAge(60 * 60 * 24 * 7);
                response.addCookie(c1);
                Cookie c2 = new Cookie("loginPwd", loginPwd);
                c2.setMaxAge(60 * 60 * 24 * 7);
                response.addCookie(c2);
            }

            // 登录成功后将用户的信息存放到session中
            request.getSession().setAttribute(AppConstant.SESSION_USER, user);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result.SUCCESS();
    }

    // 退出功能
    @RequestMapping("/settings/qx/user/logout.do")
    public String crmQuit(HttpServletRequest request) {
        request.getSession().invalidate();
        return "settings/qx/user/login";
    }
}
